<template>
	<view class="container">
		<!-- 商品信息表单 -->
		<view class="form-card">
			<view class="form-item">
				<text class="label">商品图片</text>
				<view class="upload-box">
					<view class="image-list">
						<view 
							class="image-item" 
							v-for="(item, index) in images" 
							:key="index"
						>
							<image :src="item" mode="aspectFill"></image>
							<view class="delete-btn" @click="deleteImage(index)">
								<uni-icons type="close" size="12" color="#fff"></uni-icons>
							</view>
						</view>
						<view class="upload-btn" @click="chooseImage" v-if="images.length < 6">
							<uni-icons type="camera-filled" size="24" color="#999"></uni-icons>
							<text>上传图片</text>
						</view>
					</view>
					<text class="tips">最多上传6张图片</text>
				</view>
			</view>

			<view class="form-item">
				<text class="label">商品名称</text>
				<input 
					type="text" 
					v-model="formData.title" 
					placeholder="请输入商品名称"
					class="input"
				/>
			</view>

			<view class="form-item">
				<text class="label">商品描述</text>
				<textarea
					v-model="formData.desc"
					placeholder="请输入商品描述"
					class="textarea"
					maxlength="200"
				></textarea>
				<text class="word-count">{{formData.desc.length}}/200</text>
			</view>

			<view class="form-item">
				<text class="label">商品价格</text>
				<input 
					type="digit" 
					v-model="formData.price" 
					placeholder="请输入商品价格"
					class="input"
				/>
			</view>

			<view class="form-item">
				<text class="label">商品库存</text>
				<input 
					type="number" 
					v-model="formData.stock" 
					placeholder="请输入商品库存"
					class="input"
				/>
			</view>

			<view class="form-item">
				<text class="label">赠送规则</text>
				<view class="rule-list">
					<view class="rule-item" v-for="(rule, index) in formData.giftRules" :key="index">
						<view class="rule-content">
							<text class="label-text">满</text>
							<input 
								type="number" 
								v-model="rule.buyNum" 
								placeholder="购买数量"
								class="input buy-num"
							/>
							<text class="separator">件送</text>
							<input 
								type="number" 
								v-model="rule.giftNum" 
								placeholder="赠送数量"
								class="input gift-num"
							/>
							<text class="separator">件</text>
						</view>
						<view class="delete-rule" @click="deleteRule(index)">
							<uni-icons type="trash" size="16" color="#999"></uni-icons>
						</view>
					</view>
					
					<view class="add-rule" @click="addRule">
						<uni-icons type="plus" size="16" color="#666"></uni-icons>
						<text>添加规则</text>
					</view>
				</view>
				<text class="tips">购买件数需递增</text>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="footer">
			<button class="submit-btn" @click="submitForm">发布商品</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getCurrentInstance } from 'vue'
import { config } from '@/utils/config.js'

const { proxy } = getCurrentInstance()

// 表单数据
const formData = ref({
	title: '',
	desc: '',
	price: '',
	stock: '',
	giftRules: []  // 改为 buyNum 而不是 minAmount
})

// 商品图片
const images = ref([])

// 选择并上传图片
const chooseImage = () => {
	uni.chooseImage({
		count: 6 - images.value.length,
		success: (res) => {
				uploadImages(res.tempFilePaths)
		}
	})
}

// 封装多图上传方法
const uploadFiles = (filePaths) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: config.baseUrl + '/api/goods/upload',
			filePath: filePaths[0],
			name: 'file',
			header: {
				'content-type': 'multipart/form-data'
			},
			success: (uploadRes) => {
				try {
					const data = JSON.parse(uploadRes.data)
					resolve(data)
				} catch (e) {
					reject(e)
				}
			},
			fail: (err) => {
				console.error('Upload failed:', err)
				reject(err)
			}
		})
	})
}

// 上传图片到服务器
const uploadImages = async (tempFilePaths) => {
	try {
		uni.showLoading({
			title: '上传中...'
		})
		
		// 逐个上传图片
		for (let path of tempFilePaths) {
			const res = await uploadFiles([path])
			if (res.code === 200) {
				const imageUrl = config.baseUrl + res.data.url
				images.value.push(imageUrl)
			}
		}
		
		uni.hideLoading()
		uni.showToast({
			title: '上传成功',
			icon: 'success'
		})
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: '图片上传失败',
			icon: 'none'
		})
		console.error('Upload error:', error)
	}
}

// 删除图片
const deleteImage = (index) => {
	images.value.splice(index, 1)
}

// 添加规则
const addRule = () => {
	formData.value.giftRules.push({
		buyNum: '',  // 改为购买数量
		giftNum: ''
	})
}

// 删除规则
const deleteRule = (index) => {
	formData.value.giftRules.splice(index, 1)
}

// 修改规则验证
const validateRules = () => {
	const rules = formData.value.giftRules
	if (!rules.length) return true
	
	// 检查是否有空值
	if (rules.some(rule => !rule.buyNum || !rule.giftNum)) {
		uni.showToast({
			title: '请完善赠送规则',
			icon: 'none'
		})
		return false
	}
	
	// 检查购买数量是否递增
	for (let i = 1; i < rules.length; i++) {
		if (Number(rules[i].buyNum) <= Number(rules[i-1].buyNum)) {
			uni.showToast({
				title: '购买件数需递增',
				icon: 'none'
			})
			return false
		}
	}
	
	// 检查数量是否为正整数
	if (rules.some(rule => 
		!Number.isInteger(Number(rule.buyNum)) || 
		!Number.isInteger(Number(rule.giftNum)) ||
		Number(rule.buyNum) <= 0 ||
		Number(rule.giftNum) <= 0
	)) {
		uni.showToast({
			title: '数量必须为正整数',
			icon: 'none'
		})
		return false
	}
	
	return true
}

// 获取页面参数
const initFormData = () => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const goods = currentPage.options.goods
	
	if (goods) {
		try {
			const goodsData = JSON.parse(decodeURIComponent(goods))
			// 填充表单数据
			formData.value = {
				id: goodsData.id,
				title: goodsData.title,
				desc: goodsData.desc,
				price: goodsData.price,
				stock: goodsData.stock,
				giftRules: goodsData.giftRules || []
			}
			
			// 处理图片数据
			if (goodsData.cover_image) {
				images.value.push(config.baseUrl + goodsData.cover_image)
			}
			if (goodsData.imageUrls && goodsData.imageUrls.length) {
				goodsData.imageUrls.forEach(url => {
					if (!url.startsWith('http')) {
						images.value.push(config.baseUrl + url)
					} else {
						images.value.push(url)
					}
				})
			}
		} catch (error) {
			console.error('Parse goods data error:', error)
		}
	}
}

// 修改提交方法
const submitForm = async () => {
	// 表单验证
	if (!images.value.length) {
		return uni.showToast({
			title: '请上传商品图片',
			icon: 'none'
		})
	}
	if (!formData.value.title) {
		return uni.showToast({
			title: '请输入商品名称',
			icon: 'none'
		})
	}
	if (!formData.value.desc) {
		return uni.showToast({
			title: '请输入商品描述',
			icon: 'none'
		})
	}
	if (!formData.value.price) {
		return uni.showToast({
			title: '请输入商品价格',
			icon: 'none'
		})
	}
	if (!formData.value.stock) {
		return uni.showToast({
			title: '请输入商品库存',
			icon: 'none'
		})
	}
	
	if (!validateRules()) return
	
	// 构造请求参数
	const requestData = {
		...formData.value,
		price: Number(formData.value.price),
		stock: Number(formData.value.stock),
		giftRules: formData.value.giftRules.map(rule => ({
			buyNum: Number(rule.buyNum),
			giftNum: Number(rule.giftNum)
		})),
		imageUrls: images.value.map(url => {
			const urlParts = url.split('/uploads/')
			return urlParts[1]
		})
	}
	
	try {
		const url = formData.value.id 
			? `/api/goods/${formData.value.id}`  // 修改编辑接口路径
			: '/api/goods/publish'
			
		const method = formData.value.id ? 'PUT' : 'POST'  // 编辑使用 PUT 方法
		
		const res = await uni.request({
			url: config.baseUrl + url,
			method,  // 根据是否有 id 使用不同的请求方法
			data: requestData,
			header: {
				'Authorization': uni.getStorageSync('token')
			}
		})
		
		if (res.data.code === 200) {
			uni.showToast({
				title: formData.value.id ? '更新成功' : '发布成功',
				icon: 'success',
				success: () => {
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				}
			})
		} else {
			throw new Error(res.data.message)
		}
	} catch (error) {
		console.error(formData.value.id ? '更新商品失败:' : '发布商品失败:', error)
		uni.showToast({
			title: formData.value.id ? '更新失败' : '发布失败',
			icon: 'none'
		})
	}
}

// 在页面加载时初始化数据
onMounted(() => {
	initFormData()
})
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background: #f7f8fa;
	padding-bottom: 120rpx;
}

.form-card {
	background: #fff;
	margin: 20rpx;
	border-radius: 12rpx;
	padding: 0 30rpx;
	
	.form-item {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
		
		&:last-child {
			border-bottom: none;
		}
		
		.label {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
			margin-bottom: 20rpx;
			display: block;
		}
		
		.input {
			height: 80rpx;
			background: #f7f8fa;
			border-radius: 12rpx;
			padding: 0 20rpx;
			font-size: 28rpx;
		}
		
		.upload-box {
			.image-list {
				display: flex;
				flex-wrap: wrap;
				margin: 0 -10rpx;
				
				.image-item {
					width: 160rpx;
					height: 160rpx;
					margin: 10rpx;
					position: relative;
					
					image {
						width: 100%;
						height: 100%;
						border-radius: 8rpx;
					}
					
					.delete-btn {
						position: absolute;
						top: -10rpx;
						right: -10rpx;
						width: 40rpx;
						height: 40rpx;
						background: rgba(0,0,0,0.5);
						border-radius: 20rpx;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
				
				.upload-btn {
					width: 160rpx;
					height: 160rpx;
					margin: 10rpx;
					background: #f7f8fa;
					border-radius: 8rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					
					text {
						font-size: 24rpx;
						color: #999;
						margin-top: 10rpx;
					}
				}
			}
			
			.tips {
				font-size: 24rpx;
				color: #999;
				margin-top: 20rpx;
				display: block;
			}
		}
		
		.textarea {
			width: 100%;
			height: 200rpx;
			background: #f7f8fa;
			border-radius: 12rpx;
			padding: 20rpx;
			font-size: 28rpx;
			box-sizing: border-box;
		}
		
		.word-count {
			font-size: 24rpx;
			color: #999;
			text-align: right;
			margin-top: 10rpx;
			display: block;
		}
	}
}

.footer {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	padding: 20rpx 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	
	.submit-btn {
		height: 80rpx;
		background: #ff6b81;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}

.rule-list {
	.rule-item {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		
		.rule-content {
			flex: 1;
			display: flex;
			align-items: center;
			background: #f7f8fa;
			border-radius: 12rpx;
			padding: 0 20rpx;
			
			.label-text {
				font-size: 28rpx;
				color: #666;
				margin-right: 20rpx;
			}
			
			.input {
				&.buy-num {
					width: 120rpx;
				}
				
				&.gift-num {
					width: 120rpx;
				}
			}
			
			.separator {
				font-size: 28rpx;
				color: #666;
				padding: 0 20rpx;
			}
		}
		
		.delete-rule {
			padding: 20rpx;
			margin-left: 10rpx;
		}
	}
	
	.add-rule {
		height: 80rpx;
		background: #f7f8fa;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 20rpx;
		
		text {
			font-size: 28rpx;
			color: #666;
			margin-left: 10rpx;
		}
		
		&:active {
			background: darken(#f7f8fa, 2%);
		}
	}
}

.tips {
	font-size: 24rpx;
	color: #999;
}
</style> 